﻿package {
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLRequest;
	public class LoaderQueue extends EventDispatcher {
		public function LoaderQueue() {
			init();
		}

		private var _queue:Array;
		private var _isBusy:Boolean;

		private function init():void {
			_queue = [];
			_isBusy = false;
		}
		public function push(req:URLRequest, res:Object):Boolean {
			if (!(res && res.hasOwnProperty("load"))) return false;

			var isInQueue:Boolean = false;
			var i:int = _queue.length;
			while (--i > -1) {
				if (_queue[i].request == req) {
					isInQueue = true;
					break;
				}
			}
			var now:Date = new Date();
			if (!isInQueue) _queue.push(new Item(req, res, now.getTime()));

			if (!_isBusy && _queue.length > 0) {
				var q0:Item = _queue[0];
				var req:URLRequest = q0.request;
				var rs:Object = q0.response;
				rs.addEventListener(Event.COMPLETE, onResponse);
				rs.addEventListener(IOErrorEvent.IO_ERROR, onResponse);
				rs.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onResponse);
				rs.load(req);
				_isBusy = true;
				var dt:Date = new Date(q0.date);
				trace(dt.getHours() + ':' + dt.getMinutes() + ':' + dt.getSeconds() + ':' + dt.getMilliseconds() + ' ' + req.method + ' ' + req.url);
			}
			return true;
		}
		private function onResponse(evt:Event):void {
			var res:EventDispatcher = evt.currentTarget as EventDispatcher;
			res.removeEventListener(Event.COMPLETE, onResponse);
			res.removeEventListener(IOErrorEvent.IO_ERROR, onResponse);
			res.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onResponse);

			var q0:Item = _queue[0];
			var now:Date = new Date();
			var dtime:Number = now.getTime() - q0.date;
			trace(now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds() + ':' + now.getMilliseconds() + ' ' + evt.type + ' ' + dtime + "ms");

			_isBusy = false;
			_queue.shift();
			if (_queue.length > 0) {
				q0 = _queue[0];
				push(q0.request, q0.response);
			}
		}
	}
}
// queue helper
import flash.net.URLRequest;
class Item {
	public var request:URLRequest;
	public var response:Object;
	public var date:Number;
	public function Item(req:URLRequest, res:Object, dt:Number) {
		request = req;
		response = res;
		date = dt;
	}
}
